package com.jd.myaaaccount.service;

import com.ibm.micro.client.mqttv3.MqttCallback;
import com.ibm.micro.client.mqttv3.MqttClient;
import com.ibm.micro.client.mqttv3.MqttConnectOptions;
import com.ibm.micro.client.mqttv3.MqttDeliveryToken;
import com.ibm.micro.client.mqttv3.MqttException;
import com.ibm.micro.client.mqttv3.MqttMessage;
import com.ibm.micro.client.mqttv3.MqttSecurityException;
import com.ibm.micro.client.mqttv3.MqttTopic;
import com.ibm.micro.client.mqttv3.internal.MemoryPersistence;
import com.jd.myaaaccount.MainActivity;
import com.jd.myaaaccount.util.HttpHelper;

import android.R;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;

public class SubscribeService extends Service {

	private String[] topics;
	private int[] qos;
	private NotificationManager nm;
	private PendingIntent pi;

	MqttClient mqtt;
	MqttConnectOptions option;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.e("PPPPPPPSSSSSSSS", "onStartCommand");
		initMQTT();

		initNotification();
		try {

			mqtt.setCallback(new MqttCallback() {
				@Override
				public void messageArrived(MqttTopic arg0, MqttMessage arg1)
						throws Exception {
					Log.e("PPPPPPPSSSSSSSS", "messageArrived");
					handleSubscribe(arg1.toString());
				}

				@Override
				public void deliveryComplete(MqttDeliveryToken arg0) {
					Log.e("PPPPPPPSSSSSSSS", "deliveryComplete");
				}

				@Override
				public void connectionLost(Throwable arg0) {
					Log.e("PPPPPPPSSSSSSSS", "connectionLost");

					try {// 重新连接
						mqtt.connect(option);
						mqtt.subscribe(topics, qos);
					} catch (MqttSecurityException e) {
						e.printStackTrace();
					} catch (MqttException e) {
						e.printStackTrace();
					}
				}
			});

			new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						mqtt.connect(option);
						mqtt.subscribe(topics, qos);
					} catch (MqttSecurityException e) {
						e.printStackTrace();
					} catch (MqttException e) {
						e.printStackTrace();
					}
				}
			}).start();
		} catch (MqttException e1) {
			e1.printStackTrace();
		}
		return super.onStartCommand(intent, START_STICKY, startId);
	}

	@Override
	public void onDestroy() {
		Log.e("PPPPPPPSSSSSSSS", "onDestroy");
		Intent intent = new Intent("com.jd.myaaaccount.action.SUBSCRIBE");
		startService(intent);
		super.onDestroy();
	}

	private void initMQTT() {
		TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		try {
			mqtt = new MqttClient(HttpHelper.MQTT_BROKER_URL, tm.getDeviceId(),
					new MemoryPersistence());
		} catch (MqttException e) {
			e.printStackTrace();
		}
		option = new MqttConnectOptions();
		option.setUserName("jd");
		option.setPassword("888888".toCharArray());
		option.setConnectionTimeout(6000);
		option.setCleanSession(false);
		option.setKeepAliveInterval(6000);

		topics = new String[3];
		topics[0] = "JOIN/#";
		topics[1] = "ADD_DAYBOOK/#";
		topics[2] = "#";
		qos = new int[3];
		for (int i = 0; i < qos.length; i++) {
			qos[i] = 1;
		}
	}

	private void initNotification() {
		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Intent intent = new Intent(SubscribeService.this, MainActivity.class);
		pi = PendingIntent.getActivity(SubscribeService.this, 0, intent, 0);

	}

	@SuppressLint("NewApi")
	private void handleSubscribe(String message) {
		Notification not = new Notification.Builder(this)
				.setAutoCancel(true)
				.setTicker("新消息")
				.setContentTitle("添加新记录")
				.setContentText(message)
				.setSmallIcon(R.drawable.ic_input_get)
				.setDefaults(
						Notification.DEFAULT_SOUND
								| Notification.DEFAULT_LIGHTS
								| Notification.DEFAULT_VIBRATE)
				.setWhen(System.currentTimeMillis()).setContentIntent(pi)
				.build();
		nm.notify(1, not);
	}
}
